package com.mm.fam.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.fam.common.utils.LoggerUtils;
import com.mm.fam.web.base.ResponseModel;
import com.mm.fam.web.base.ResponseUtil;
import com.mm.fam.web.entity.SysPermission;
import com.mm.fam.web.entity.SysRole;
import com.mm.fam.web.entity.SysRolePermission;
import com.mm.fam.web.entity.ins.PermissionTreeIns;
import com.mm.fam.web.mapper.SysMenuMapper;
import com.mm.fam.web.mapper.SysPermissionMapper;
import com.mm.fam.web.mapper.SysRoleMapper;
import com.mm.fam.web.mapper.SysRolePermissionMapper;
import com.mm.fam.web.service.SysPermissionService;
import com.mm.fam.web.vo.MenuOperateAccredit;
import com.mm.fam.web.vo.MenuPermissionTree;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zt
 * @since 2018-09-29
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public List<SysPermission> getPermissionByUserId(Integer userId) {
        return sysPermissionMapper.getPermissionByUserId(userId);
    }

    @Override
    public ResponseEntity<ResponseModel<Object>> savePermission(SysPermission permission) throws RuntimeException {
        ResponseEntity<ResponseModel<Object>> re = null;
        Date date=new Date();
        if(permission.getId()!=null){
            permission.setUpdateTime(date);
            updateById(permission);
            re = ResponseUtil.success(null);
        }else {
            permission.setCreateTime(date);
            permission.setUpdateTime(date);
            save(permission);

            //新增资源后 向所有角色追加资源
            List<SysRole> sysRoles = sysRoleMapper.selectList(new QueryWrapper<SysRole>());
            for(SysRole sysRole : sysRoles){
                SysRolePermission srp = new SysRolePermission();
                srp.setRoleId(sysRole.getId());
                srp.setPermId(permission.getId());
                srp.setStatus(0);
                sysRolePermissionMapper.insert(srp);
            }
            re = ResponseUtil.success(null);
        }
        return re;
    }

    @Override
    public IPage<SysPermission> page(int pageNum, int pageSize, String search, Integer parentId) {

        QueryWrapper<SysPermission> wrapper = new QueryWrapper<>();

        search= StringUtils.trim(search);
        if (StringUtils.isNoneEmpty(search)) {
            wrapper.like(true,"name","%" + search + "%");
        }
        if(parentId!=null){
            wrapper.eq(true,"parent_id",parentId);
        }
        wrapper.orderBy(true,true,"level");
        wrapper.orderBy(true,true,"id");
        Page<SysPermission>page = new Page<>(pageNum,pageSize);
        return sysPermissionMapper.selectPage(page,wrapper);
    }

    @Override
    public List<SysPermission> getPermissionByParentId(Integer parentId) {
        QueryWrapper<SysPermission> wrapper = new QueryWrapper<>();
        if (parentId!=null) {
            wrapper.eq(true,"parent_id",parentId);
        }
        return sysPermissionMapper.selectList(wrapper);
    }

    @Override
    public Page<PermissionTreeIns> getPermissionTree(int pageNum, int pageSize, String parentId, String name) {
        Page<PermissionTreeIns>   page = new Page<>(pageNum,pageSize);
        try {

            Map<String,Object>map=new HashMap<>();
            map.put("parentId",parentId);
            map.put("name",name.trim());
            if (!StringUtils.isEmpty(name)) {
                map.put("query_name",name);
            }else
            { map.put("query_name","");
            }
            map.put("page",page);
            List<PermissionTreeIns> lists = sysPermissionMapper.getPermissionTree(map);
            page.setRecords(lists);
        }catch (Exception e)
        {
            e.printStackTrace();
        }

        return page;
    }

    @Override
    public List<PermissionTreeIns> getPermissionTree(Integer parentId) {
        Map<String,Object> map=new HashMap<>();
        map.put("parentId",parentId);
        map.put("query_name","");
        List<PermissionTreeIns> lists = sysPermissionMapper.getPermissionTree(map);
        return lists;
    }

    @Override
    public List<SysPermission> getPermissionByRoleId(Integer roleId) {
        return sysPermissionMapper.getPermissionByRoleId(roleId);
    }


    @Override
    public String deleteBatch(List<String>ids) throws  RuntimeException{
        try {
            if (!ids.isEmpty() && ids.size()>0)
            {
                for (String id:ids)
                {
                    int index= sysPermissionMapper.queryPermIdByPermissionCount(id);
                    if (index<=0)
                    {
                        sysPermissionMapper.deleteBatchIds(ids);
                    }else
                    {
                        throw new RuntimeException("当前资源被占用，请核实以后再操作！");
                    }
                }
            }

        } catch (Exception e) {
            LoggerUtils.error(getClass(), "权限资源删除失败:" + e.getMessage());
            throw new RuntimeException("删除失败");
        }
        return "删除成功";
    }

    @Override
    public List<MenuOperateAccredit> getRoleEnableOperateAccreditList(Integer roleId) {
        return sysPermissionMapper.queryRoleEnableOperateAccreditList(roleId);
    }

    @Override
    public ResponseEntity<ResponseModel<IPage<MenuPermissionTree>>> queryMenuPermissionList(int pageNo, int pageSize, String search) {
        ResponseEntity<ResponseModel<IPage<MenuPermissionTree>>> re = null;
        Map<String, Object> paramMap = new HashMap<>();
        if(search != null){
            paramMap.put("search", '%'+search+'%');
        }
        Page<MenuPermissionTree> page = new Page<>(pageNo, pageSize);
        IPage<MenuPermissionTree> menuPermissionTreeIPage = page.setRecords(sysMenuMapper.menuPermissionTreeList(page, paramMap));

        re = ResponseUtil.success(menuPermissionTreeIPage);

        return re;
    }
}
